<template>
  <el-dialog v-model="visible" title="用户登录" width="350px" :close-on-click-modal="false" class="login-dialog">
    <el-form :model="form" label-width="60px" class="login-form" @submit.prevent>
      <el-form-item label="用户名">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitLogin">登录</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore();

const props = defineProps({ modelValue: Boolean })
const emit = defineEmits(['update:modelValue', 'login-success'])

const visible = ref(props.modelValue)
watch(() => props.modelValue, val => visible.value = val)
watch(visible, val => emit('update:modelValue', val))

const form = ref({
  username: '',
  password: '',
})

const submitLogin = async () => {
  if (!form.value.username || !form.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  try {
    const userData = await userStore.login(form.value)
    emit('login-success', userData)
    ElMessage.success('登录成功')
    visible.value = false
  } catch (e) {
    ElMessage.error(`登录失败：${e.message}`)
  }
}
</script>

<style scoped>
.login-dialog {
  font-family: Arial, sans-serif;
}

.login-form {
  margin-top: 10px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.el-input input {
  font-size: 14px;
}
</style>
